package com.mall.order.services;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mall.order.OrderQueryService;
import com.mall.order.constant.OrderRetCode;
import com.mall.order.converter.OrderConverter;
import com.mall.order.dal.entitys.*;
import com.mall.order.dal.persistence.OrderItemMapper;
import com.mall.order.dal.persistence.OrderMapper;
import com.mall.order.dal.persistence.OrderShippingMapper;
import com.mall.order.dto.*;
import com.mall.order.utils.ExceptionProcessorUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import tk.mybatis.mapper.entity.Example;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 *  cskaoyan
 */
@Slf4j
@Component
@Service
public class OrderQueryServiceImpl implements OrderQueryService {

    @Autowired
    OrderMapper orderMapper;

    @Autowired
    OrderItemMapper orderItemMapper;

    @Autowired
    OrderShippingMapper orderShippingMapper;

    @Autowired
    OrderConverter orderConverter;

    /**
     * 查看用户所有订单
     * @param request
     * @return
     */
    @Override
    public OrderListResponse getOrdersByUserId(OrderListRequest request) {

        OrderListResponse response = new OrderListResponse();

        try{
            // 校验请求参数的有效性
            request.requestCheck();

            // 配置分页信息，第几页、每一页有多少数据
            PageHelper.startPage(request.getPage(), request.getSize());
            // 构造条件数据
            Example example=new Example(Order.class);
            example.createCriteria().andEqualTo("userId",request.getUserId());
            // 设置排序
            String sort = request.getSort();
            if(sort != null && "".equals(sort)){
                example.setOrderByClause(sort);
            }

            List<Order> orders = orderMapper.selectByExample(example);

            PageInfo<Order> pageInfo = new PageInfo<>(orders);


            // 订单详细信息的查询
            List<OrderDetailInfo> orderDetailList = new ArrayList<>();

            for (Order order : orders) {
                OrderDetailInfo orderDetailInfo = orderConverter.order2detail(order);

                // 查询订单-商品中间表
                List<OrderItem> orderItems = orderItemMapper.queryByOrderId(order.getOrderId());
                orderDetailInfo.setOrderItemDto(orderConverter.item2dto(orderItems));

                // 查询订单的收货人表
                OrderShipping orderShipping = orderShippingMapper.selectByPrimaryKey(order.getOrderId());
                orderDetailInfo.setOrderShippingDto(orderConverter.shipping2dto(orderShipping));

                orderDetailList.add(orderDetailInfo);
            }

            response.setDetailInfoList(orderDetailList);	// 订单详细列表
            response.setTotal(pageInfo.getTotal());	// 订单总数
            response.setCode(OrderRetCode.SUCCESS.getCode());
            response.setMsg(OrderRetCode.SUCCESS.getMessage());
        }catch (Exception e){
            log.error("OrderCoreServiceImpl.getOrdersByUserId occur Exception :"+e);
            ExceptionProcessorUtils.wrapperHandlerException(response,e);
        }
        return response;

    }

    /**
     * 查询订单详情信息
     * @param request
     * @return
     */
    @Override
    public QueryOrderResponse getOrderById(OrderDetailRequest request) {

        QueryOrderResponse response = new QueryOrderResponse();

        try{
            // 校验请求参数的有效性
            request.requestCheck();

            String orderId = request.getOrderId();
            // 查询order表，该订单的详细信息
            Order order = orderMapper.selectByPrimaryKey(orderId);

            Long userId = order.getUserId();
            String userName = order.getBuyerNick();
            BigDecimal orderTotal = order.getPayment();
            Integer orderStatus = order.getStatus();

            // 查询order_shipping表，该订单的地址信息
            OrderShipping orderShipping = orderShippingMapper.selectByPrimaryKey(orderId);
            String streetName = orderShipping.getReceiverAddress();
            String tel = orderShipping.getReceiverPhone();

            // 查询order_item表，该订单包含的所有商品的信息
            List<OrderItemDto> goodsList = orderConverter.item2dto(orderItemMapper.queryByOrderId(orderId));

            // 封装数据
            QueryOrderData data = new QueryOrderData();
            data.setUserName(userName);
            data.setOrderTotal(orderTotal);
            data.setUserId(userId);
            data.setGoodsList(goodsList);
            data.setTel(tel);
            data.setStreetName(streetName);
            data.setOrderStatus(orderStatus);

            response.setData(data);
            response.setCode(OrderRetCode.SUCCESS.getCode());
            response.setMsg(OrderRetCode.SUCCESS.getMessage());

        } catch (Exception e){
            log.error("OrderCoreServiceImpl.getOrderById occur Exception :"+e);
            ExceptionProcessorUtils.wrapperHandlerException(response,e);
        }
        return response;

    }

}
